{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 高频交易策略分析\n",
    "\n",
    "本笔记本实现常见高频交易策略"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "import numpy as np\n",
    "import matplotlib.pyplot as plt\n",
    "from datetime import datetime, timedelta\n",
    "\n",
    "# 设置中文显示\n",
    "plt.rcParams['font.sans-serif'] = ['SimHei']\n",
    "plt.rcParams['axes.unicode_minus'] = False"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 数据准备"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def simulate_tick_data(symbol='600519', days=5):\n",
    "    \"\"\"\n",
    "    模拟生成tick数据\n",
    "    \n",
    "    Args:\n",
    "        symbol: 股票代码\n",
    "        days: 模拟天数\n",
    "        \n",
    "    Returns:\n",
    "        pd.DataFrame: tick数据\n",
    "    \"\"\"\n",
    "    try:\n",
    "        # 获取日线数据作为基础\n",
    "        df = ak.stock_zh_a_hist(symbol=symbol, period=\"daily\", adjust=\"qfq\")\n",
    "        close = df['收盘'].iloc[-1]\n",
    "        \n",
    "        # 生成tick数据\n",
    "        ticks = []\n",
    "        for day in range(days):\n",
    "            date = datetime.now() - timedelta(days=day)\n",
    "            for sec in range(4*60*60):  # 4小时交易时间\n",
    "                if sec % 5 == 0:  # 每5秒一个tick\n",
    "                    price = close * (1 + np.random.normal(0, 0.0005))\n",
    "                    volume = np.random.randint(1, 100)\n",
    "                    ticks.append({\n",
    "                        'symbol': symbol,\n",
    "                        'time': date.replace(hour=9, minute=30) + timedelta(seconds=sec),\n",
    "                        'price': round(price, 2),\n",
    "                        'volume': volume\n",
    "                    })\n",
    "        return pd.DataFrame(ticks).set_index('time').sort_index()\n",
    "    except Exception as e:\n",
    "        print(f\"生成tick数据失败: {e}\")\n",
    "        return pd.DataFrame()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 做市商策略"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def market_making_strategy(ticks, spread=0.01, position_limit=1000):\n",
    "    \"\"\"\n",
    "    简单做市商策略\n",
    "    \n",
    "    Args:\n",
    "        ticks: tick数据\n",
    "        spread: 买卖价差\n",
    "        position_limit: 头寸限制\n",
    "        \n",
    "    Returns:\n",
    "        pd.DataFrame: 包含交易信号和头寸\n",
    "    \"\"\"\n",
    "    try:\n",
    "        df = ticks.copy()\n",
    "        df['mid'] = df['price'].rolling(10).mean()  # 中间价\n",
    "        df['bid'] = df['mid'] - spread/2  # 买价\n",
    "        df['ask'] = df['mid'] + spread/2  # 卖价\n",
    "        \n",
    "        # 生成信号\n",
    "        df['signal'] = 0\n",
    "        df.loc[df['price'] <= df['bid'], 'signal'] = 1  # 买入信号\n",
    "        df.loc[df['price'] >= df['ask'], 'signal'] = -1  # 卖出信号\n",
    "        \n",
    "        # 计算头寸\n",
    "        df['position'] = df['signal'].cumsum()\n",
    "        df['position'] = df['position'].clip(-position_limit, position_limit)\n",
    "        \n",
    "        return df\n",
    "    except Exception as e:\n",
    "        print(f\"做市商策略执行失败: {e}\")\n",
    "        return pd.DataFrame()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 主分析流程"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 生成模拟tick数据\n",
    "ticks = simulate_tick_data()\n",
    "\n",
    "# 运策略\n",
    "result = market_making_strategy(ticks)\n",
    "\n",
    "# 绘制结果\n",
    "plt.figure(figsize=(12, 6))\n",
    "result['price'].plot(label='价格')\n",
    "result['bid'].plot(label='买价', style='g--')\n",
    "result['ask'].plot(label='卖价', style='r--')\n",
    "plt.scatter(result.index, result['price'].where(result['signal']==1), \n",
    "            color='g', label='买入信号')\n",
    "plt.scatter(result.index, result['price'].where(result['signal']==-1), \n",
    "            color='r', label='卖出信号')\n",
    "plt.title('做市商策略信号')\n",
    "plt.legend()\n",
    "plt.grid()\n",
    "plt.show()"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}